﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace YuFeng.Web.Extentions
{
    public static class StringExtentions
    {
        public static string ToQueryString(this object obj)
        {
            IList<string> properties = new List<string>();

            foreach (var p in obj.GetType().GetProperties())
            {

                if (p.PropertyType == typeof(string[]))
                {
                    var values = p.GetValue(obj) as string[];
                    if (values != null)
                    {
                        var valuesNotEmpty = values.Where(o => !String.IsNullOrEmpty(o)).ToArray();
                        if (valuesNotEmpty.Length > 0)
                        {
                            foreach (var s in valuesNotEmpty)
                            {
                                var item = p.Name + "=" + s.UrlEncode();
                                properties.Add(item);
                            }
                        }
                    }
                    continue;
                }

                if (p.PropertyType == typeof(decimal[]))
                {
                    var values = p.GetValue(obj) as decimal[];
                    if (values != null)
                    {
                        var valuesNotEmpty = values.Where(o => o > 0).ToArray();
                        if (valuesNotEmpty.Length > 0)
                        {
                            foreach (var s in valuesNotEmpty)
                            {
                                var item = p.Name + "=" + s;
                                properties.Add(item);
                            }
                        }
                    }
                    continue;
                }

                var value = p.GetValue(obj, null);
                if (value != null)
                {
                    var item = p.Name + "=" + p.GetValue(obj, null).ToString().UrlEncode();
                    properties.Add(item);
                }
            }
            return String.Join("&", properties.ToArray());
        }
        public static string UrlEncode(this string str)
        {
            StringBuilder builder = new StringBuilder();
            foreach (char c in str)
            {
                var urlEncode = HttpUtility.UrlEncode(c.ToString());
                if (!String.IsNullOrEmpty(urlEncode))
                {
                    builder.Append(urlEncode);
                }
                else
                {
                    builder.Append(c.ToString());
                }
            }
            return builder.ToString();
        }
    }
}